/**
 * Created by Administrator on 2017/8/29.
 */
var map;
var busStationIcon = new BMap.Icon("img/busstation_marker.png", new BMap.Size(10, 10)); //沿途各站平时用busStationIcon标识
var busStationFocusIcon = new BMap.Icon("img/busstation_marker_focus.png", new BMap.Size(10, 10));
var startMarkerIcon = new BMap.Icon("img/startmarker.png", new BMap.Size(20, 20));
var endMarkerIcon = new BMap.Icon("img/endmarker.png", new BMap.Size(20, 20));
var infoWindow = new BMap.InfoWindow(""); //点击该图标弹出信息窗infoWindow来显示该站的名字和经过它的公交线路

var busutil;

var hasbusNo01 = false;
var curItemNo01 = window.localStorage.getItem("curItemNo01");
if(curItemNo01 == null){
    curItemNo01 = 0;
    window.localStorage.setItem("curItemNo01", curItemNo01);
}
var busNo01 = window.localStorage.getItem("busNo01");
if(busNo01 != null){
    hasbusNo01 = true;
}
var haskeyword01 = false;
var keyword01 = window.localStorage.getItem("keyword01");
if(keyword01 != null){
    haskeyword01 = true;
}

var pointsArr = [];
var markerArr = [];
var busStationArr = [];


$(document).ready(function () {
    initMap();
    initControl();
    ReverseControl.prototype = new BMap.Control();

    ReverseControl.prototype.initialize = function (map) {
        var img = document.createElement("img");
        img.style.cursor = 'pointer';
        img.setAttribute('src', 'img/reversebutton.png');
        img.setAttribute('width', '40px');
        img.setAttribute('height', '40px');
        map.getContainer().appendChild(img);
        img.onclick = function (e) {
            curItemNo01 = 1 - curItemNo01;
            window.localStorage.setItem('curItemNo01', curItemNo01);
            busutil.getBusList(busNo01);
        };
        return img;
    };

    var myReverseControl = new ReverseControl();
    map.addControl(myReverseControl);

    //对面板进行声明
    $("#searchpanel").trigger("updatelayout");
    $("#resultpanel").trigger("updatelayout");

    busutil = new BMap.BusLineSearch(map, {
        renderOptions: {panel: "itemResult"},
        onGetBusListComplete: function (buslist) {
            //考虑环线
            if (buslist.getBusListItem(curItemNo01) == undefined) {
                curItemNo01 = 0;
                window.localStorage.setItem('curItemNo01', curItemNo01);
            }
            busutil.getBusLine(buslist.getBusListItem(curItemNo01));
        },
        onGetBusLineComplete: function (busline) {
            var polyline = new BMap.Polyline(busline.getPath(), {
                strokeColor: "#3333FF",
                strokeWeight: 5,
                strokeOpacity: 0.7
            });
            map.clearOverlays();
            map.addOverlay(polyline);
            showPolyline(busline);
        },
        onBusLineHtmlSet: function () {
            //线路格式化完毕时 才执行 所以在这里添加marker是不能显示的
//            setStartEndMarker(tempVar);
            $("#l-result ul li a").each(function (index, element) {
                if ($(element).html() != busNo01) {
                    $(element).css("color", "green");
                } else {
                    $(element).css("color", "blue");
                }
            });
        }
    });

    if(hasbusNo01&&haskeyword01){
        //限定搜索杭州
        new BMap.LocalSearch("杭州", {
            onSearchComplete: function () {
                busutil.getBusList(busNo01);
            }
        }).search(keyword01);
        hasbusNo01 = false;
        haskeyword01 = false;
    }

    document.getElementById('query').onclick = function () {
        map.clearOverlays();
        keyword01 = document.getElementById('keyword01').value;
        window.localStorage.setItem('keyword01', keyword01);
        new BMap.LocalSearch("杭州", {
            onSearchComplete: searchComplete
        }).search(keyword01+"公交车站");

        $("#keyword01").val("");

        //当线路切换的时候 清空
        pointsArr = [];
        markerArr = [];
        busStationArr = [];

        $("#searchpanel").panel("close");
        $("#resultpanel").panel("open");
    };

/*    document.getElementById('reversequery').onclick = function () {
        curItemNo01 = 1 - curItemNo01;
        busutil.getBusList(busNo01);
    };*/
});

function ReverseControl(){
    // 默认停靠位置和偏移量
    this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
    this.defaultOffset = new BMap.Size(0, 40);
}

function searchComplete(result) {
    var html = [];
    for (var i = 0; i < result.getCurrentNumPois(); i++) {
        var poi = result.getPoi(i);
        if (poi.type == BMAP_POI_TYPE_BUSSTOP) {
            var busNames = poi.address.split(';');
            for (i = 0; i < busNames.length; i++) {
                //获得了所有的busName 把它写到div中
                html.push('<li><a href="javascript:void(0)" onclick="subgo(\'' + busNames[i] + '\')">' +
                    busNames[i] +
                    '</a></li>');
            }
        } else {

        }
    }
    var l_result = document.getElementById("l-result");
    l_result.innerHTML = '<ul>' + html.join('') + '</ul>';
}

function showPolyline(busline) {
    for (var i = 0; i < busline.getNumBusStations(); i++) {
        var busStation = busline.getBusStation(i);
        pointsArr[i] = busStation.position;
        busStationArr[i] = busStation.name;
        if (i == 0) {
            addCircle(i, busline, busStation, startMarkerIcon);
        } else if (i == busline.getNumBusStations() - 1) {
            addCircle(i, busline, busStation, endMarkerIcon);
        } else {
            if(busStation.name == keyword01){
                addCircle(i, busline, busStation, busStationFocusIcon);
            }else{
                addCircle(i, busline, busStation, busStationIcon);
            }
        }
    }
    map.setViewport(pointsArr);
    busStationArr.forEach(function (value, index) {
        if(value==keyword01){
            var event = new CustomEvent("click");
            markerArr[index].dispatchEvent(event);
        }
    });
}

function addCircle(index, busline, busStation, icon) {
    var marker = new BMap.Marker(busStation.position, {icon: icon});
    markerArr[index] = marker;
    marker.setTitle(busStation.name);
    marker.addEventListener("click", function () {
        infoWindow.setTitle(busStation.name + " (" + busline.name + ")");
        keyword01 = busStation.name;
        window.localStorage.setItem('keyword01', keyword01);
        //前台给后端SL_ID（StopLine 公交线路站点表的主键
        //后台返回给前端两个信息 最近一辆公交正在开往--站，据此--分钟--米
        //如果有第二辆公交的信息，那么也进行显示
        $.ajax({
            url: 'http://10.100.122.132/busStationInfo',
//                data: {"SL_id":sl_id},
            type: 'get',
            datatype: 'json',
            async: 'false',
            success: function (json) {
                var busInfoList = json.station;
                var infoArr = [];
                for (var i in busInfoList) {
                    infoArr[i] = "最近第" + (parseInt(i) + 1) + "辆公交车正在开往" + busInfoList[i].nextstop + "，距本站" +
                        busInfoList[i].stopcount +
                        "站，" + busInfoList[i].distance + "，需要" + busInfoList[i].time;

                }
                //markerArr 所有marker
                markerArr.forEach(function (value, index) {
                    if(value.getIcon()==busStationFocusIcon){
                        value.setIcon(busStationIcon);
                        return false;
                    }
                });

                if(marker.getIcon()==busStationIcon){
                    marker.setIcon(busStationFocusIcon);
                }
                infoWindow.setContent(infoArr[0] + "</br>" + infoArr[1]);
                marker.openInfoWindow(infoWindow);
            }
        });
    });
    map.addOverlay(marker);
}

function subgo(itemNo) {
    busNo01 = itemNo;
    window.localStorage.setItem("busNo01", busNo01);
    busutil.getBusList(busNo01);
}


//初始化地图
initMap = function () {
    var mapOpts = {minZoom: 11, maxZoom: 17, enableHighResolution: true};
    map = new BMap.Map('map', mapOpts);
    map.centerAndZoom("杭州");
};

//初始化地图控件
initControl = function () {
    var navOpts = {anchor: BMAP_ANCHOR_BOTTOM_RIGHT, offset: new BMap.Size(50, 40), type: BMAP_NAVIGATION_CONTROL_ZOOM};
    var nav = new BMap.NavigationControl(navOpts);
    map.addControl(nav);

    /*    var scale = new BMap.ScaleControl();
     map.addControl(scale);*/

    var overOpts = {
        anchor: BMAP_ANCHOR_TOP_LEFT,
        offset: new BMap.Size(10, 10),
        size: new BMap.Size(100, 100),
        isOpen: false
    };
    var over = new BMap.OverviewMapControl(overOpts);
    map.addControl(over);

    /*    var mapTypeC = new BMap.MapTypeControl();
     map.addControl(mapTypeC);*/
};